﻿using Abp.Dependency;
using Abp.Timing;
using Abp.Timing.Timezone;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using System;

namespace AbpProjectTemplate.Utilities.Json
{
    public class DateTimeJsonConverter : IsoDateTimeConverter
    {
        private readonly string _format;
        public DateTimeJsonConverter(string format = "yyyy-MM-dd HH:mm:ss") {
            this._format = format;
        }

        public override bool CanConvert(Type objectType)
        {
            return objectType == typeof(DateTime) || objectType == typeof(DateTime?);
        }

        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
        {
            var date = base.ReadJson(reader, objectType, existingValue, serializer) as DateTime?;

            if (date.HasValue)
            {
                return Clock.Normalize(date.Value);
            }

            return null;
        }

        public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
        {
            var date = value as DateTime?;
            var val = date.HasValue ? Clock.Normalize(date.Value).ToString(this._format) : value;
            //base.WriteJson(writer, val, serializer);
            writer.WriteValue(val);
        }

    }
}
